package com.mtech.modbus_rtu;

import com.mtech.aircdx.AirCdxReader;
import com.mtech.aircdx.AirCdxWriter;
import com.mtech.modbus_rtu.codec.impl.ModbusRTUCodec;
import com.mtech.modbus_rtu.data._03.MultiReadRxDataGram;
import com.mtech.modbus_rtu.data._03.MultiReadTxDataGram;
import com.mtech.modbus_rtu.util.ByteUtils;

/**
 * 使用例子<br>
 * 详细可以查看{@link com.mtech.modbus_rtu.DataGramTest}
 * 
 * @author lixiaolong
 * @CreateDate 2018年3月20日
 */
public class Demo {
	static ModbusRTUCodec codec = ModbusRTUCodec.getInstance();

	public static void main(String args[]) {
		//查询设备01的0004H房卡状态
		MultiReadTxDataGram tx = new MultiReadTxDataGram(0x01, 0x0004, 0x01);
		byte[] buf = codec.encode(tx);
		//byte [] buf = tx.toBytes();//等价于上一条
		System.out.println("查询房卡状态报文:" + ByteUtils.parseByte2HexStr(buf));

		//设备响应查询
		byte[] resp = new byte[] { 0x01, 0x03, 0x02, 0x00, 0x01, (byte) 0x79, (byte) 0x84 };
		//MultiReadRxDataGram rx = new MultiReadRxDataGram((byte) 0x01, new int[] { 0x0001 });
		//MultiReadRxDataGram rx = new MultiReadRxDataGram(resp);//实际使用中此处的resp应为从流中读取而来
		MultiReadRxDataGram rx = (MultiReadRxDataGram) codec.decodeRx(resp);
		System.out.println("设备反馈报文:" + ByteUtils.parseByte2HexStr(rx.toBytes()));
		System.out.println("房卡状态为:" + rx.getRegDatas()[0]);

		//或者这样
		//读取0x03设备所有寄存器状态
		AirCdxReader acr = AirCdxReader.getInstance(0x03);
		byte[] buf2 = acr.readAll();
		System.out.println("查询设备所有寄存器报文:" + ByteUtils.parseByte2HexStr(buf2));

		//设置0x03设备的温度为26度
		AirCdxWriter acw = AirCdxWriter.getInstance(0x01);
		byte[] buf3 = acw.writePowerState(1);
		System.out.println("设备温度设定报文:" + ByteUtils.parseByte2HexStr(buf3));
	}
}
